package com.nyist.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.nyist.pojo.User;
import com.nyist.result.CommonResult;
import com.nyist.service.PayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;

@RestController
public class CircleBreakerController {

    @Value("${service-url.nacos-user-service}")
    private String url;

    @Resource
    private RestTemplate restTemplate;


    @GetMapping(value = "/consumer/fallback/{id}")
    //没有配置
    //@SentinelResource(value = "fallback")

    //fallback 只负责异常
    //@SentinelResource(value = "fallback",fallback = "handlerFallback")

    //blockHandler 只负责sentinel 控制台配置违规
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler")

    //fallback 、 blockHandler 都配置  会触发blockHandler
    //exceptionsToIgnore 表示 忽略该异常
    @SentinelResource(value = "fallback",
            blockHandler = "blockHandler",
            fallback = "handlerFallback",
            exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult fallback(@PathVariable("id") Integer id){
        CommonResult result = restTemplate.getForObject(url + "/paySQL/" + id, CommonResult.class);

        if(id==4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        }else if(result.getData()==null){
            throw new NullPointerException("NullPointerException,该id没有对应记录，空指针异常");
        }
        return result;
    }
    //本侧是 fallback，只负责业务异常
    public CommonResult handlerFallback(@PathVariable("id") Integer id,Throwable e){
        User user = new User(id,"fallback 兜底方法",10);
        return new CommonResult("444","兜底异常handlerFallback，exception内容："+e.getMessage(),user);
    }

    //本侧是 blockHandler，只负责sentinel 控制台配置违规
    public CommonResult blockHandler(@PathVariable("id") Integer id, BlockException e){
        User user = new User(id,"blockHandler限流",20);
        return new CommonResult("445","blockHandler限流，exception内容："+e.getMessage(),user);
    }


    //============openfeign

    @Resource
    private PayService service;

    @GetMapping("/consumer/paySQL/{id}")
    public CommonResult paySQL(@PathVariable("id")Integer id){
        return service.paySQL(id);
    }

}
